import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import ColumnDetail from '../views/ColumnDetail.vue'
import CreatePost from '../views/CreatePost.vue'
import store from '../store'
import axios from 'axios'
const routes= [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta:{redirectAlreadyLogin:true}
  },
  // "params": {"id": "1"}
  {
    path:'/column/:id',
    name:'colomn',
    component:ColumnDetail
  },
  {
    path:'/createPost',
    name:'createPost',
    component:CreatePost,
    meta:{requiredLogin:true}
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})
router.beforeEach((to,from,next)=>{
  // if(to.name!=='login'&&!store.state.user.isLogin){
  //   next({name:'login'})
  // }else if(to.meta.redirectAlreadyLogin && store.state.user.isLogin){
  //   next('/')
  // }else{
  //   next()
  // }

  const {user,token}=store.state
  const {requiredLogin,redirectAlreadyLogin}=to.meta
  if(!user.isLogin){
    if(token){
      axios.defaults.headers.common.Authorization=`Bearer ${token}`
      store.dispatch('fetchCurrentUser').then(()=>{
        if(redirectAlreadyLogin){
          next('/')
        }else{
          next()
        }
      }).catch(e=>{
        console.error(e)
        store.commit('logout')
        next('login')
      })
    }else{
      if(requiredLogin){
        next('login')
      }else{
        next()
      }
    }
  }else{
    if(redirectAlreadyLogin){
      next('/')
    }else{
      next()
    }
  }
})

export default router